﻿using System;
using System.Diagnostics;
using System.Linq;
using System.ServiceModel;

/*
	CRM Namespaces
	--------------
	Remember to add the following references from the CRM SDK \bin folder
		Microsoft.Xrm.Client.dll
		Microsoft.Xrm.Sdk.dll
*/
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Messages;


namespace CRM_2011_Auto_Counter
{
    public class Auto_Counter : IPlugin
    {
        public void Execute(IServiceProvider serviceProvider)
        {
            IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

            // TODO - If you require tracing, uncomment the following line
            // ITracingService trace = (ITracingService)serviceProvider.GetService(typeof(ITracingService));

            Entity entity = null;

            // Check if the InputParameters property bag contains a target
            // of the current operation and that target is of type DynamicEntity.
            if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
            {
                // Obtain the target business entity from the input parmameters.
                entity = (Entity)context.InputParameters["Target"];

                //// TODO Test for an entity type and message supported by your plug-in.
                //if (context.PrimaryEntityName != "<entity logical name>") { return; }
                //if (context.MessageName != "<message>") { return; }
            }
            else
            {
                return;
            }

            try
            {
                IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

                // TODO - Plugin code goes here
                Servicescontext sc = new Servicescontext(service);

                var counter = sc.new_counterSet.ToList().Where(c => c.new_name.ToLower() == entity.LogicalName.ToLower()).ToList<new_counter>();
                if (counter.Count > 0)
                {
                    string counterValue = Convert.ToInt64(counter.First().new_NextNumber).ToString();

                    counterValue = counter.First().new_Prefix+addZero(counterValue, counter.First().new_Length)+counter.First().new_Suffix;

                    //set next number
                    counter.First().new_NextNumber = counter.First().new_NextNumber + counter.First().new_Increment;
                       
                    sc.UpdateObject(counter.First());
                    sc.SaveChanges();

                    //set counter to target entity
                    if (entity.Attributes.Contains(counter.First().new_TargetField))
                    {
                        entity.Attributes[counter.First().new_TargetField.ToString()] = counterValue;
                    }
                    else
                    {
                        entity.Attributes.Add(counter.First().new_TargetField.ToString(), counterValue);
                    }
                }
                else
                {
                    throw new InvalidPluginExecutionException("No matched counter configuration found. Please check counter configuration in setting area.");
                }
            }
            catch (FaultException<OrganizationServiceFault> ex)
            {
                throw new InvalidPluginExecutionException("An error occurred in the plug-in.", ex);
            }
        }

        private string addZero(string input, int? Length)
        {
            if (Length == null)
            {
                Length = 8;
            }
            string localString = input;
            for (int i = input.Length; i < Length; i++)
            {
                localString = "0" + localString;
            }

            return localString;
        }
    }
}
